import Toast from 'tdesign-miniprogram/toast/index';
import Message from 'tdesign-miniprogram/message/index';
import {
  fetchData, checkAuctionMoney
} from '../../../services/good/fetchGood';

import {
  cdnBase
} from '../../../config/index';
import moment from 'moment'
import request from '../../../utils/request'

const imgPrefix = `${cdnBase}/`;

const recLeftImg = `${imgPrefix}common/rec-left.png`;
const recRightImg = `${imgPrefix}common/rec-right.png`;

const obj2Params = (obj = {}, encode = false) => {
  const result = [];
  Object.keys(obj).forEach((key) =>
    result.push(`${key}=${encode ? encodeURIComponent(obj[key]) : obj[key]}`),
  );
  return result.join('&');
};

Page({
  data: {
    confirmBtn: { content: '确定', variant: 'base' },
    priceTitle: '',
    showPriceExp: false,
    isShowPromotionPop: false,
    recLeftImg,
    recRightImg,
    details: {},
    isSpuSelectPopupShow: false,
    navigation: {
      type: 'fraction'
    },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    isFixedTop: false,
    popupVisible: false,
    userId: getApp().globalData.userInfo == null ? 0 : getApp().globalData.userInfo.id,
    showPrice: 0,
    startSecond: 0, //开始倒计时
    endSecond: 0,//结束倒计时

    lastPriceTime: '', //最后出价赶时间
    serverTime: '' //当前服务器时间
  },
  myInterval: null,
  onScroll(e) {
    this.setData({ isFixedTop: e.detail.isFixed })
  },
  onPageScroll({
    scrollTop
  }) {
    const goodsTab = this.selectComponent('#goodsTab');
    goodsTab && goodsTab.onScroll(scrollTop);
  },
  handlePopupHide() {
    this.setData({
      popupVisible: false,
    });
  },
  getDetail(id) {
    Promise.all([fetchData(id), checkAuctionMoney(id, 2)]).then((res) => {
      console.log("res", res)
      res = JSON.parse(JSON.stringify(res))
      const [details, hasPaid] = res;
      // details.type = this.data.type;
      // details.status = this.data.status;
      // details.marginPrice = getRandomNum(1000, 5000);
      // if (details.status == 1) {
      //   details.startTime = moment(details.startTime).format("MM月DD日HH:mm");
      // } else if (details.status == 2) {
      //   details.endTime = moment(details.endTime).format("MM月DD日HH:mm");
      // }
      // if (details.status == 2) {
      //   this.getLastInfo();
      // }
      // this.setData({
      //   details
      // });
      var currentAcution = getApp().globalData.currentAuction;
      console.log("currentAcution", currentAcution);

      // details.packageName = currentAcution.packageName;
      // details.carPrice = currentAcution.carPrice;
      details.carImages = currentAcution.carImages;
      // details.newPrice = currentAcution.newPrice;
      // details.signNum = currentAcution.signNum;
      // details.makePriceNum = currentAcution.makePriceNum;

      details.type = details.auctionType;
      details.status = details.auctionFlag;

      //按开始时间重置拍卖状态
      if (moment().isBefore(details.config.startTime)) {
        details.status = 0;
      }
      // if(moment(details.config.endTime).isBefore(moment())){
      //   details.status = 2;
      // }

      var hours = moment(details.config.endTime)
        .diff(moment(details.config.startTime),
          "hours")

      details.cycle = hours + "小时";
      // details.residueSecond = moment(details.config.endTime)
      //   .diff(moment(),
      //     "seconds")
      //离开始时间
      var startSecond = moment(details.config.startTime)
        .diff(moment(),
          "seconds") * 1000
      //离结束时间
      var endSecond = moment(details.config.endTime)
        .diff(moment(),
          "seconds") * 1000
      if (details.auctionType == 2) {
        if (details.lastPriceTime != null) {
          var et = moment(details.lastPriceTime).add(details.config.auctionDuration, 'second');
          endSecond = moment(et)
            .diff(moment(),
              "seconds") * 1000
        }
      }
      console.log(hours, details.startSecond, details.endSecond)
      details.startTime = moment(details.config.startTime).format("MM月DD日HH:mm");
      details.endTime = moment(details.config.endTime).format("MM月DD日HH:mm");

      for (var j = 0; j < details.cars.length; j++) {
        var data = details.cars[j];
        if (data.evaImages != null && data.evaImages != "") {
          var imgs = data.evaImages.split(',');
          for (var i = 0; i < imgs.length; i++) {
            imgs[i] = getApp().globalData.imageUrl + imgs[i];
          }
          data.evaImages = imgs;
        }
      }
      details.hasPaid = hasPaid;

      this.setData({ details: details, startSecond: startSecond, endSecond: endSecond }, () => {
        this.checkPriceShow()
      });

      if (details.status == 1 && details.hasPaid == 1) {
        this.getLastInfo();
      }
    });
  },
  onStartSecondCountDownFinish() {
    this.getDetail(this.data.id);
    if (this.myInterval != null) {
      clearInterval(this.myInterval)
    }
  },
  //报名，交保证金
  onSignUp() {
    var that = this;
    var userInfo = getApp().getUserInfoByLocal();
    if (userInfo == null) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请先注册成为车商再进行拍卖',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    if (userInfo.flag == 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '您的信息还未通过审核',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    this.setData({ showPriceExp: true, priceTitle: '您是否要缴纳' + this.data.details.bondMoney + '元保证金 ？' })
    // wx.showModal({
    //   content: '您是否要缴纳' + this.data.details.bondMoney + '元保证金 ？',
    //   success(res) {
    //     if (res.confirm) {
    //       that.callPay()
    //     }
    //   }
    // })
  },
  callPay() {
    var that = this;
    var details = that.data.details;
    this.setData({ showPriceExp: false })
    // request.post("car/pay/requestPay?money=0.01&openid=" + getApp().globalData.openid, {
    //   money: 0.01,
    //   openid: getApp().globalData.openid
    // }, function (res) {
    //   if (res.code == 0) {
    //     console.log("call pay:", res)
    //     that.setData({ payInfo: res.data })
    //     that.wxPay();

    //   } else {
    //     Toast({
    //       context: that,
    //       selector: '#t-toast',
    //       message: res.message,
    //       theme: 'error',
    //       direction: 'column',
    //     });
    //   }
    // })
    // Toast({
    //   context: this,
    //   selector: '#t-toast',
    //   message: '正在模拟支付...',
    //   theme: 'loading',
    //   direction: 'column',
    //   duration: 5000
    // });

    var url = "/car/user/dealer/addAuctionMoney?auctionId=" + details.id + "&type=1";
    request.post(url, null, function (res) {
      if (res.code == 0) {
        console.log("call pay:", res)
        that.setData({ payInfo: res.data })
        that.wxPay();
      } else {
        Toast({
          context: that,
          selector: '#t-toast',
          message: res.message,
          theme: 'error',
          direction: 'column',
        });
      }
    })

    // Toast({
    //   context: that,
    //   selector: '#t-toast',
    //   message: '支付成功',
    //   theme: 'success',
    //   direction: 'column',
    // });

  },
  closeDialog() {
    this.setData({ showPriceExp: false });
  },

  submitSignUp() {
    var that = this;
    var details = this.data.details;
    if (details.auctionType == 1) {
      //固定价格购买
      wx.showModal({
        content: '您是否确定购买？',
        success(res) {
          if (res.confirm) {
            var url = "/car/user/dealer/buyWithPrice?id=" + details.id;
            request.post(url, null, function (res) {
              if (res.code == 0) {
                details.signNum++;
                details.auctionFlag = 2;
                details.status = 2;
                that.setData({ details: details })
              } else {
                Toast({
                  context: that,
                  selector: '#t-toast',
                  message: res.message,
                  theme: 'error',
                  direction: 'column',
                });
              }
            })
          }
        }
      })


    }
    // details.joinNum++;
    // if (details.auctionType == 1) {
    //   details.status = 3;
    // } else {
    //   details.hasPaid = 1;
    // }
    // this.setData({ details: details });
  },
  onAddPrice() {
    this.setData({
      popupVisible: true,
    });
  },
  onPopupVisibleChange(e) {
    this.setData({
      popupVisible: e.detail.visible,
    });
  },
  submitAddPrice() {
    var that = this;
    var details = this.data.details;
    var url = "/car/user/dealer/buyWithAuction?auctionId=" + details.id + "&price=" + details.config.addingPrice;
    request.post(url, null, function (res) {
      if (res.code == 0) {
        Toast({
          context: that,
          selector: '#t-toast',
          message: "加价成功",
          theme: 'success',
          direction: 'column',
        });
      } else {
        Message.warning({
          context: this,
          offset: [20, 32],
          duration: 2000,
          content: res.message,
        });
      }
    })

    // details.currentPrice = parseInt(details.currentPrice) + parseInt(details.stepMoney);
    // details.quotationNum++;
    this.setData({
      details: details,
      popupVisible: false,
    });
  },
  getLastInfo() {
    var that = this;
    if (this.myInterval != null) {
      clearInterval(this.myInterval)
    }
    this.myInterval = setInterval(function () {
      var details = that.data.details;
      var url = "/car/user/dealer/lastInfo?auctionId=" + details.id;
      request.post(url, null, function (res) {
        if (res.code == 0) {
          var { makePriceNum, newPrice, signNum, lastDealerId, lastPriceTime, serverTime } = res.data;
          if (details.newPrice != newPrice) {
            Message.success({
              context: that,
              offset: [20, 32],
              duration: 3000,
              content: '有新的报价',
            });
          }

          details.newPrice = newPrice;
          details.makePriceNum = makePriceNum;
          details.signNum = signNum;
          console.log("lastDealerId", lastDealerId, that.data.userId)
          details.newPriceDealer = lastDealerId

          that.setData({ details: details, lastPriceTime: lastPriceTime, serverTime: serverTime }, () => {
            that.checkPriceShow()
            that.changeEndSecond();
            console.log("lastDealerId", lastDealerId, that.data.userId, that.data.details.newPriceDealer)
          });
        }
      })
    }, 10000);
  },
  wxPay: function () {
    var that = this;
    var details = that.data.details;
    var payInfo = this.data.payInfo;
    var signType = 'MD5';
    if (payInfo.signType) {
      signType = payInfo.signType
    }
    wx.requestPayment({
      'timeStamp': payInfo.timeStamp,
      'nonceStr': payInfo.nonceStr,
      'package': payInfo.packageVal,
      'signType': signType,
      'paySign': payInfo.paySign,
      'success': function (res) {
        details.hasPaid = 1;
        details.signNum++;
        that.setData({ details: details }, () => {
          that.checkPriceShow();
          that.getLastInfo();
        })
        Toast({
          context: that,
          selector: '#t-toast',
          message: '支付成功',
          theme: 'success',
          direction: 'column',
        });
      },
      'fail': function (res) {
        console.log("error:", res)
        wx.showToast({ icon: 'none', title: '支付失败' })
        that.setData({ result: "error" })
      }
    })
  },
  checkPriceShow() {
    var details = this.data.details;
    if (getApp().globalData.userInfo != null && getApp().globalData.userInfo.flag != 0 && details.hasPaid == 1) {
      this.setData({ showPrice: 1 })
    }
  },
  changeEndSecond() {
    var { details, lastPriceTime } = this.data;
    var endSecond = 0;
    if (details.auctionType == 2) {
      if (lastPriceTime != null) {
        var et = moment(lastPriceTime).add(details.config.auctionDuration, 'second');
        endSecond = moment(et)
          .diff(moment(),
            "seconds") * 1000

        this.setData({ endSecond: endSecond })
      }
    }
  },

  onLoad(query) {
    const {
      id, type, status
    } = query;
    this.setData({
      id: id, type: type, status: status
    });
    this.getDetail(id);
  },
  onUnload() {
    if (this.myInterval != null) {
      clearInterval(this.myInterval)
    }
  }
});